﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
using KPIS.GERP.GIMS.BLL;
using KPIS.GERP.GIMS.IBLL;
using KPIS.GERP.GIMS.MODEL;
using System.Data;

namespace KPIS.GERP.GIMS.APP.APP_UI.Edit_Form
{
    public partial class ICM_Master_Contact : System.Web.UI.Page
    {
        Common.Main cn = new Common.Main();
        CommandControl cmdFac = new CommandControl();
        IBLLMasterContact bll = new MasterContactBLL();
        IBLLMasterContactBank bllBank = new MasterContactBankBLL();
        IBLLMasterContactPartner bllPartner = new MasterContactPartnerBLL();
        IBLLSysContactGroup bllGroup = new SysContactGroupBLL();
        IBLLSysContactStatus bllStatus = new SysContactStatusBLL();
        IBLLSysVat bllVat = new SysVatBLL();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadContactGroup();
                LoadContactStatus();
                LoadVat();
                GetKeyValue();
            }
        }

        protected void RadTabStrip1_TabClick(object sender, RadTabStripEventArgs e)
        {
            if (RadTabStrip1.SelectedTab.Value == "Detail")
            {
                GetKeyValue();
            }
            else if (RadTabStrip1.SelectedTab.Value == "Address")
            {
                LoadAddress();
            }
            else if (RadTabStrip1.SelectedTab.Value == "Bank")
            {
                LoadGridBank();
            }
            else if (RadTabStrip1.SelectedTab.Value == "Partner")
            {
                LoadGridPartner();
            }
        }

        public void GetKeyValue()
        {
            string day = "";
            string month = "";
            string year = "";
            int contact_seq = Convert.ToInt32(Request.QueryString["Seq"]);
            MasterContactInfo info = bll.GetMasterContact(Convert.ToInt32(contact_seq));

            cbGroup.SelectedValue = info.InfoGroup.Seq.ToString();
            txtNameTh.Text = info.Name_th;
            txtNameEn.Text = info.Name_eng;
            txtCoordinator.Text = info.Coordinator;
            txtGfmis.Text = info.Gfmis_code;
            txtTax.Text = info.Tax_code;
            cbVat.SelectedValue = info.InfoVat.Seq.ToString();
            txtRegCapital.Value = info.Reg_capital;
            string[] all_date = info.Reg_date.ToString().Split('/');
            if (all_date[0].Length > 0)
            {
                if (all_date[0].Length < 2)
                {
                    day = "0" + all_date[0];
                }
                else
                {
                    day = all_date[0];
                }
                if (all_date[1].Length < 2)
                {
                    month = "0" + all_date[1];
                }
                else
                {
                    month = all_date[1];
                }

                year = all_date[2];
                txtDate.Text = day + "/" + month + "/" + year;
            }
            rblStatus.SelectedValue = info.InfoStatus.Seq.ToString();
            
            cmdFac.ViewCommand(panelList_Detail, panelGrid_Detail, panelCommand_Detail);
        }

        public void LoadAddress()
        {
            int contact_seq = Convert.ToInt32(Request.QueryString["Seq"]);
            MasterContactInfo info = bll.GetMasterContact(Convert.ToInt32(contact_seq));

            txtCountry.Text = info.Country;
            txtAddress.Text = info.Address;
            txtBuilding.Text = info.Building;
            txtFloor.Text = info.Floor;
            txtVillage.Text = info.Village;
            txtRoad.Text = info.Road;
            txtLane.Text = info.Lane;
            txtDistrict.Text = info.District;
            txtAmphur.Text = info.Amphur;
            txtPost.Text = info.Post;
            txtProvince.Text = info.Province;
            txtTel.Text = info.Tel;
            txtTelNext.Text = info.Tel_next;
            txtFax.Text = info.Fax;
            txtFaxNext.Text = info.Fax_next;
            txtEmail.Text = info.Email;

            cmdFac.ViewCommand(panelList_Address, panelGrid_Address, panelCommand_Address);
        }


        public void GetBankValue(string seq)
        {
            if (seq.Length > 0)
            {
                MasterContactBankInfo info = bllBank.GetMasterContactBank(Convert.ToInt32(seq));

                txtBankCode.Text = info.Code;
                txtBankName.Text = info.Name;
                txtBankBranch.Text = info.Branch;
                txtAccountCode.Text = info.Account_code;
                txtAccountName.Text = info.Account_name;

                cmdFac.ViewCommand(panelList_Bank, panelGrid_Bank, panelCommand_Bank);
            }
        }

        public void GetPartnerValue(string seq)
        {
            if (seq.Length > 0)
            {
                MasterContactPartnerInfo info = bllPartner.GetMasterContactPartner(Convert.ToInt32(seq));

                txtPartnerName.Text = info.Name;
                txtPartnerCitizen.Text = info.Citizen;
                txtPartnerDescr.Text = info.Descr;

                cmdFac.ViewCommand(panelList_Partner, panelGrid_Partner, panelCommand_Partner);
            }
        }

        public void LoadContactGroup()
        {
            IList<SysContactGroupInfo> info = bllGroup.GetSysContactGroup();
            cbGroup.DataSource = info;
            cbGroup.DataBind();
        }

        public void LoadContactStatus()
        {
            IList<SysContactStatusInfo> info = bllStatus.GetSysContactStatus();
            rblStatus.DataSource = info;
            rblStatus.DataBind();
        }

        public void LoadVat()
        {
            IList<SysVatInfo> info = bllVat.GetSysVat();
            cbVat.DataSource = info;
            cbVat.DataBind();
        }

        public void LoadGridBank()
        {
            int contact_seq = Convert.ToInt32(Request.QueryString["Seq"]);
            Grid_Bank.DataSource = bllBank.GetMasterContactBankWithParent(contact_seq);
            Grid_Bank.DataBind();

            cmdFac.GridCommand(panelList_Bank, panelGrid_Bank, panelCommand_Bank);
        }

        public void LoadGridPartner()
        {
            int contact_seq = Convert.ToInt32(Request.QueryString["Seq"]);
            Grid_Partner.DataSource = bllPartner.GetMasterContactPartnerWithParent(contact_seq);
            Grid_Partner.DataBind();

            cmdFac.GridCommand(panelList_Partner, panelGrid_Partner, panelCommand_Partner);
        }

        protected void Edit_Detail_Click(object sender, EventArgs e)
        {
            cmdFac.EditCommand(panelList_Detail, panelGrid_Detail, panelCommand_Detail);
            LoadValiDateDetail();
        }

        protected void EditSave_Detail_Click(object sender, EventArgs e)
        {
            int contact_seq = Convert.ToInt32(Request.QueryString["Seq"]);
            MasterContactInfo info = new MasterContactInfo();
            SysContactGroupInfo infoGroup = new SysContactGroupInfo();
            SysContactStatusInfo infoStatus = new SysContactStatusInfo();
            SysVatInfo infoVat = new SysVatInfo();
            RecordInfo infoRecord = new RecordInfo();

            info.Seq = Convert.ToInt32(contact_seq);
            infoGroup.Seq = Convert.ToInt32(cbGroup.SelectedValue);
            info.Name_th = txtNameTh.Text;
            info.Name_eng = txtNameEn.Text;
            info.Coordinator = txtCoordinator.Text;
            info.Gfmis_code = txtGfmis.Text;
            info.Tax_code = txtTax.Text;
            infoVat.Seq = Convert.ToInt32(cbVat.SelectedValue);
            info.Reg_capital = txtRegCapital.Value;
            if (txtDate.Text.Length > 0)
            {
                info.Reg_date = Convert.ToDateTime(txtDate.TextWithLiterals);
            }
            infoStatus.Seq = Convert.ToInt32(rblStatus.SelectedValue);
            infoRecord.Updated_by = Int32.Parse(Session["EmpSeq"].ToString());
            infoRecord.Updated_when = DateTime.Now;
            info.InfoGroup = infoGroup;
            info.InfoStatus = infoStatus;
            info.InfoVat = infoVat;
            info.InfoRecord = infoRecord;

            try
            {
                bll.Update(info);
            }
            catch
            {
                RadManager1.Alert(SystemInfo._InsertError);
                return;
            }

            GetKeyValue();
        }

        protected void Cancel_Detail_Click(object sender, EventArgs e)
        {
            cmdFac.CancelCommand(panelList_Detail, panelGrid_Detail, panelCommand_Detail);
        }

        protected void Edit_Address_Click(object sender, EventArgs e)
        {
            cmdFac.EditCommand(panelList_Address, panelGrid_Address, panelCommand_Address);
        }

        protected void EditSave_Address_Click(object sender, EventArgs e)
        {
            int contact_seq = Convert.ToInt32(Request.QueryString["Seq"]);
            MasterContactInfo info = new MasterContactInfo();
            SysContactGroupInfo infoGroup = new SysContactGroupInfo();
            SysContactStatusInfo infoStatus = new SysContactStatusInfo();
            SysVatInfo infoVat = new SysVatInfo();
            RecordInfo infoRecord = new RecordInfo();

            info.Seq = Convert.ToInt32(contact_seq);
            info.Country = txtCountry.Text;
            info.Address = txtAddress.Text;
            info.Building = txtBuilding.Text;
            info.Floor = txtFloor.Text;
            info.Village = txtVillage.Text;
            info.Road = txtRoad.Text;
            info.Lane = txtLane.Text;
            info.District = txtDistrict.Text;
            info.Amphur = txtAmphur.Text;
            info.Post = txtPost.Text;
            info.Province = txtProvince.Text;
            info.Tel = txtTel.Text;
            info.Tel_next = txtTelNext.Text;
            info.Fax = txtFax.Text;
            info.Fax_next = txtFaxNext.Text;
            info.Email = txtEmail.Text;
            infoRecord.Updated_by = Int32.Parse(Session["EmpSeq"].ToString());
            infoRecord.Updated_when = DateTime.Now;
            info.InfoGroup = infoGroup;
            info.InfoStatus = infoStatus;
            info.InfoVat = infoVat;
            info.InfoRecord = infoRecord;

            try
            {
                bll.Update(info);
            }
            catch
            {
                RadManager1.Alert(SystemInfo._InsertError);
                return;
            }

            LoadAddress();
        }

        protected void Cancel_Address_Click(object sender, EventArgs e)
        {
            cmdFac.CancelCommand(panelList_Address, panelGrid_Address, panelCommand_Address);
        }

        protected void AddNew_Bank_Click(object sender, EventArgs e)
        {
            cmdFac.AddNewCommand(panelList_Bank, panelGrid_Bank, panelCommand_Bank);
            LoadValiDateBank();
        }

        protected void AddNewSave_Bank_Click(object sender, EventArgs e)
        {
            int contact_seq = Convert.ToInt32(Request.QueryString["Seq"]);
            MasterContactBankInfo info = new MasterContactBankInfo();
            MasterContactInfo infoContact = new MasterContactInfo();
            RecordInfo infoRecord = new RecordInfo();
            info.Code = txtBankCode.Text;
            info.Name = txtBankName.Text;
            info.Branch = txtBankBranch.Text;
            info.Account_code = txtAccountCode.Text;
            info.Account_name = txtAccountName.Text;
            infoContact.Seq = Convert.ToInt32(contact_seq);
            infoRecord.Created_by = cn.UserID;
            infoRecord.Created_when = DateTime.Now;
            info.InfoContact = infoContact;
            info.InfoRecord = infoRecord;

            try
            {
                bllBank.Insert(info);
            }
            catch
            {
                RadManager1.Alert(SystemInfo._InsertError);
                return;
            }

            LoadGridBank();
        }

        protected void Delete_Bank_Click(object sender, EventArgs e)
        {
            IList<MasterContactBankInfo> infoList = new List<MasterContactBankInfo>();
            foreach (GridDataItem data in Grid_Bank.MasterTableView.GetSelectedItems())
            {
                MasterContactBankInfo info = new MasterContactBankInfo();
                RecordInfo infoRecord = new RecordInfo();
                info.Seq = Convert.ToInt32(data.OwnerTableView.DataKeyValues[data.ItemIndex]["Seq"]);
                infoRecord.Updated_by = Int32.Parse(Session["EmpSeq"].ToString());
                infoRecord.Updated_when = DateTime.Now;
                info.InfoRecord = infoRecord;
                infoList.Add(info);
            }

            if (infoList.Count == 0)
            {
                RadManager1.Alert(SystemInfo._DeleteNull);
                return;
            }

            try
            {
                bllBank.DeleteFromDB(infoList);
            }
            catch
            {
                RadManager1.Alert(SystemInfo._DeleteError);
                return;
            }

            LoadGridBank();
        }

        protected void ShowGrid_Bank_Click(object sender, EventArgs e)
        {
            LoadGridBank();
        }

        protected void Grid_Bank_ItemCommand(object source, GridCommandEventArgs e)
        {
            LoadGridBank();
        }

        protected void Cancel_Bank_Click(object sender, EventArgs e)
        {
            cmdFac.CancelCommand(panelList_Bank, panelGrid_Bank, panelCommand_Bank);
        }

        protected void Edit_Bank_Click(object sender, EventArgs e)
        {
            cmdFac.EditCommand(panelList_Bank, panelGrid_Bank, panelCommand_Bank);
            LoadValiDateBank();
        }

        protected void EditSave_Bank_Click(object sender, EventArgs e)
        {
            int contact_seq = Convert.ToInt32(Request.QueryString["Seq"]);
            MasterContactBankInfo info = new MasterContactBankInfo();
            MasterContactInfo infoContact = new MasterContactInfo();
            RecordInfo infoRecord = new RecordInfo();
            info.Seq = Convert.ToInt32(hdSeq.Value);
            info.Code = txtBankCode.Text;
            info.Name = txtBankName.Text;
            info.Branch = txtBankBranch.Text;
            info.Account_code = txtAccountCode.Text;
            info.Account_name = txtAccountName.Text;
            infoContact.Seq = Convert.ToInt32(contact_seq);
            infoRecord.Created_by = cn.UserID;
            infoRecord.Created_when = DateTime.Now;
            info.InfoContact = infoContact;
            info.InfoRecord = infoRecord;

            try
            {
                bllBank.Update(info);
            }
            catch
            {
                RadManager1.Alert(SystemInfo._InsertError);
                return;
            }

            cmdFac.ViewCommand(panelList_Bank, panelGrid_Bank, panelCommand_Bank);
        }

        protected void AddNew_Partner_Click(object sender, EventArgs e)
        {
            cmdFac.AddNewCommand(panelList_Partner, panelGrid_Partner, panelCommand_Partner);
            LoadValiDatePartner();
        }

        protected void AddNewSave_Partner_Click(object sender, EventArgs e)
        {
            int contact_seq = Convert.ToInt32(Request.QueryString["Seq"]);
            MasterContactPartnerInfo info = new MasterContactPartnerInfo();
            MasterContactInfo infoContact = new MasterContactInfo();
            RecordInfo infoRecord = new RecordInfo();
            info.Name = txtPartnerName.Text;
            info.Citizen = txtPartnerCitizen.Text;
            info.Descr = txtPartnerDescr.Text;
            infoContact.Seq = Convert.ToInt32(contact_seq);
            infoRecord.Created_by = cn.UserID;
            infoRecord.Created_when = DateTime.Now;
            info.InfoContact = infoContact;
            info.InfoRecord = infoRecord;

            try
            {
                bllPartner.Insert(info);
            }
            catch
            {
                RadManager1.Alert(SystemInfo._InsertError);
                return;
            }

            LoadGridPartner();
        }

        protected void Delete_Partner_Click(object sender, EventArgs e)
        {
            IList<MasterContactPartnerInfo> infoList = new List<MasterContactPartnerInfo>();
            foreach (GridDataItem data in Grid_Partner.MasterTableView.GetSelectedItems())
            {
                MasterContactPartnerInfo info = new MasterContactPartnerInfo();
                RecordInfo infoRecord = new RecordInfo();
                info.Seq = Convert.ToInt32(data.OwnerTableView.DataKeyValues[data.ItemIndex]["Seq"]);
                infoRecord.Updated_by = Int32.Parse(Session["EmpSeq"].ToString());
                infoRecord.Updated_when = DateTime.Now;
                info.InfoRecord = infoRecord;
                infoList.Add(info);
            }

            if (infoList.Count == 0)
            {
                RadManager1.Alert(SystemInfo._DeleteNull);
                return;
            }

            try
            {
                bllPartner.DeleteFromDB(infoList);
            }
            catch
            {
                RadManager1.Alert(SystemInfo._DeleteError);
                return;
            }

            LoadGridPartner();
        }

        protected void ShowGrid_Partner_Click(object sender, EventArgs e)
        {
            LoadGridPartner();
        }

        protected void Grid_Partner_ItemCommand(object source, GridCommandEventArgs e)
        {
            LoadGridPartner();
        }

        protected void Cancel_Partner_Click(object sender, EventArgs e)
        {
            cmdFac.CancelCommand(panelList_Partner, panelGrid_Partner, panelCommand_Partner);
        }

        protected void Edit_Partner_Click(object sender, EventArgs e)
        {
            cmdFac.EditCommand(panelList_Partner, panelGrid_Partner, panelCommand_Partner);
            LoadValiDatePartner();
        }

        protected void EditSave_Partner_Click(object sender, EventArgs e)
        {
            int contact_seq = Convert.ToInt32(Request.QueryString["Seq"]);
            MasterContactPartnerInfo info = new MasterContactPartnerInfo();
            MasterContactInfo infoContact = new MasterContactInfo();
            RecordInfo infoRecord = new RecordInfo();
            info.Seq = Convert.ToInt32(hdSeq.Value);
            info.Name = txtPartnerName.Text;
            info.Citizen = txtPartnerCitizen.Text;
            info.Descr = txtPartnerDescr.Text;
            infoContact.Seq = Convert.ToInt32(contact_seq);
            infoRecord.Created_by = cn.UserID;
            infoRecord.Created_when = DateTime.Now;
            info.InfoContact = infoContact;
            info.InfoRecord = infoRecord;

            try
            {
                bllPartner.Update(info);
            }
            catch
            {
                RadManager1.Alert(SystemInfo._InsertError);
                return;
            }

            cmdFac.ViewCommand(panelList_Partner, panelGrid_Partner, panelCommand_Partner);
        }

        protected void RadManager1_AjaxRequest(object sender, AjaxRequestEventArgs e)
        {
            if (e.Argument == "Bank")
            {
                GetBankValue(hdSeq.Value);
            }
            if (e.Argument == "Partner")
            {
                GetPartnerValue(hdSeq.Value);
            }
        }

        protected void clearFilter_Bank_Click(object sender, EventArgs e)
        {
            foreach (GridColumn column in Grid_Bank.MasterTableView.Columns)
            {
                column.CurrentFilterFunction = GridKnownFunction.NoFilter;
                column.CurrentFilterValue = string.Empty;
            }
            Grid_Bank.MasterTableView.FilterExpression = string.Empty;
            LoadGridBank();
        }

        protected void clearFilter_Partner_Click(object sender, EventArgs e)
        {
            foreach (GridColumn column in Grid_Partner.MasterTableView.Columns)
            {
                column.CurrentFilterFunction = GridKnownFunction.NoFilter;
                column.CurrentFilterValue = string.Empty;
            }
            Grid_Partner.MasterTableView.FilterExpression = string.Empty;
            LoadGridPartner();
        }

        private void LoadValiDateDetail()
        {
            RequiredFieldValidator valGroup = new RequiredFieldValidator();
            valGroup.ID = "ValcbGroup";
            valGroup.ControlToValidate = "cbGroup";
            valGroup.SetFocusOnError = true;
            valGroup.Display = ValidatorDisplay.Dynamic;
            valGroup.ErrorMessage = "* กรุณาระบุกลุ่มผู้ขาย *";
            panelValcbGroup.Controls.Add(valGroup);
            RequiredFieldValidator valName = new RequiredFieldValidator();
            valName.ID = "ValtxtNameTh";
            valName.ControlToValidate = "txtNameTh";
            valName.SetFocusOnError = true;
            valName.Display = ValidatorDisplay.Dynamic;
            valName.ErrorMessage = "* กรุณาระบุชื่อผู้ขาย(ไทย) *";
            panelValtxtNameTh.Controls.Add(valName);
            RequiredFieldValidator valVat = new RequiredFieldValidator();
            valVat.ID = "ValcbVat";
            valVat.ControlToValidate = "cbVat";
            valVat.SetFocusOnError = true;
            valVat.Display = ValidatorDisplay.Dynamic;
            valVat.ErrorMessage = "* กรุณาระบุการคิดฐานภาษี *";
            panelValcbVat.Controls.Add(valVat);
            CustomValidator valDate = new CustomValidator();
            valDate.ID = "ValDate";
            valDate.ControlToValidate = "txtDate";
            valDate.SetFocusOnError = true;
            valDate.Display = ValidatorDisplay.Dynamic;
            valDate.ErrorMessage = "* กรุณาระบุวันที่ให้ถูกต้อง *";
            valDate.ClientValidationFunction = "validateDate";
            panelValDate.Controls.Add(valDate);
            RequiredFieldValidator valStatus = new RequiredFieldValidator();
            valStatus.ID = "ValrblStatus";
            valStatus.ControlToValidate = "rblStatus";
            valStatus.SetFocusOnError = true;
            valStatus.Display = ValidatorDisplay.Dynamic;
            valStatus.ErrorMessage = "* กรุณาระบุสถานะผู้ขาย *";
            panelValrblStatus.Controls.Add(valStatus);
        }

        private void LoadValiDateBank()
        {
            RequiredFieldValidator valCode = new RequiredFieldValidator();
            valCode.ID = "ValtxtBankCode";
            valCode.ControlToValidate = "txtBankCode";
            valCode.SetFocusOnError = true;
            valCode.Display = ValidatorDisplay.Dynamic;
            valCode.ErrorMessage = "* กรุณาระบุรหัสธนาคาร *";
            panelValtxtBankCode.Controls.Add(valCode);
            RequiredFieldValidator valName = new RequiredFieldValidator();
            valName.ID = "ValtxtBankName";
            valName.ControlToValidate = "txtBankName";
            valName.SetFocusOnError = true;
            valName.Display = ValidatorDisplay.Dynamic;
            valName.ErrorMessage = "* กรุณาระบุชื่อธนาคาร *";
            panelValtxtBankName.Controls.Add(valName);
        }

        private void LoadValiDatePartner()
        {
            RequiredFieldValidator valName = new RequiredFieldValidator();
            valName.ID = "ValPartnerName";
            valName.ControlToValidate = "txtPartnerName";
            valName.SetFocusOnError = true;
            valName.Display = ValidatorDisplay.Dynamic;
            valName.ErrorMessage = "* กรุณาระบุชื่อ-สกุลผู้ถือหุ้น *";
            panelValPartnerName.Controls.Add(valName);
            RequiredFieldValidator valCitizen = new RequiredFieldValidator();
            valCitizen.ID = "ValPartnerCitizen";
            valCitizen.ControlToValidate = "txtPartnerCitizen";
            valCitizen.SetFocusOnError = true;
            valCitizen.Display = ValidatorDisplay.Dynamic;
            valCitizen.ErrorMessage = "* กรุณาระบุหมายเลขบัตรประชาชน *";
            panelValPartnerCitizen.Controls.Add(valCitizen);
            CustomValidator valCheck = new CustomValidator();
            valCheck.ID = "ValCheckCitizen";
            valCheck.ControlToValidate = "txtPartnerCitizen";
            valCheck.SetFocusOnError = true;
            valCheck.Display = ValidatorDisplay.Dynamic;
            valCheck.ErrorMessage = "* หมายเลขบัตรประชาชนไม่ถูกต้อง *";
            valCheck.ClientValidationFunction = "ValidateCitizen";
            panelValPartnerCitizen.Controls.Add(valCheck);
        }
    }
}
